package com.nowcoder.community.controller;

import ch.qos.logback.core.util.StringUtil;
import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityUtils;
import com.nowcoder.community.util.HostHolder;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@Controller
@RequestMapping("/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Value("${server.servlet.context-path}")
    String contextpath;

    @Value("${community.path.domain}")
    String domain;

    @Value("${community.path.upload}")
    String upload;

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;


    @LoginRequired
    @RequestMapping("/setting")
    public String getSettingPage() {
        return "/site/setting";
    }

    @LoginRequired
    @RequestMapping(path="/upload", method = RequestMethod.POST)
    public String uploadHeader(MultipartFile headerImage, Model model) {
        if (headerImage ==null) {
            model.addAttribute("error","未选择图片");
            return "site/setting";
        }

        String fileName =headerImage.getOriginalFilename();
        String suffix =fileName.substring(fileName.lastIndexOf("."));
        if (StringUtil.isNullOrEmpty(suffix)) {
            model.addAttribute("error","头像后缀不正确");
            return "site/setting";
        }

        fileName= CommunityUtils.generateUUID()+suffix;
        File dest =new File(upload+"/"+fileName);
        try {
            headerImage.transferTo(dest);
        } catch (IOException e) {
            logger.error("上传头像失败"+e.getMessage());
            throw new RuntimeException(e);
        }

        User user =hostHolder.getUser();
        String headerUrl =domain+contextpath+"/user/header/"+fileName;
        int i =userService.updateHeader(user.getId(),headerUrl);
        return "redirect:/index";
    }

    @LoginRequired
    @RequestMapping(path="/update", method = RequestMethod.POST)
    public String updatePwd(String formerPassword, String nowPassword, String repeatPassword, Model model) {

        if (StringUtil.isNullOrEmpty(formerPassword)) {
            model.addAttribute("formerPasswordMsg","旧密码不能为空");
            return "site/setting";
        }

        if (StringUtil.isNullOrEmpty(nowPassword)) {
            model.addAttribute("nowPasswordMsg","新密码不能为空");
            return "site/setting";
        }

        if (StringUtil.isNullOrEmpty(repeatPassword)) {
            model.addAttribute("repeatPasswordMsg","新密码不能为空");
            return "site/setting";
        }

        User user =hostHolder.getUser();

        if (!user.getPassword().equals(CommunityUtils.md5(formerPassword+user.getSalt()))) {
            model.addAttribute("formerPasswordMsg","原始密码错误");
            return "site/setting";
        }

       if (!repeatPassword.equals(nowPassword)) {
           model.addAttribute("repeatPasswordMsg","前后密码不一致");
           return "site/setting";
       }

        int i =userService.updatePassword(user.getId(),nowPassword);
        if (i==1) {
            return "redirect:/index";
        }
        model.addAttribute("error","密码修改失败");
        return "site/setting";
    }

    @RequestMapping(path = "/header/{fileName}", method = RequestMethod.GET)
    public void getheader(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        fileName =upload+"/"+fileName;
        String suffix =fileName.substring(fileName.lastIndexOf("."));
        response.setContentType("image/"+suffix);
        try {
            OutputStream os=response.getOutputStream();
            FileInputStream fis =new FileInputStream(fileName);
            byte[] buffer =new byte[1024];
            int b;
            while ((b=fis.read(buffer)) !=-1) {
                os.write(buffer,0,b);
            }
            fis.close();
            os.close();
        } catch (Exception e) {
           logger.error("读取头像失败："+e.getMessage());
        }



    }

}
